package easyjava.function;

import java.io.Closeable;

/**
 * with 方法
 *
 */
public interface WithFunction {

    @FunctionalInterface
    interface WithCallNoReturn<T> {
        void run(T obj);
    }

    @FunctionalInterface
    interface WithCallHasReturn<T> {
        Object run(T obj);
    }

    static <T> void with(T obj, WithCallNoReturn<T> callFun) {
        try {
            callFun.run(obj);
            if(obj instanceof Closeable){
                ((Closeable) obj).close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static <T, E> E with(T obj, WithCallHasReturn<T> callFun) {
        try {
            E result = (E) callFun.run(obj);
            if(obj instanceof Closeable){
                ((Closeable) obj).close();
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
